package cn.dm.example.commonUnsafe;

import cn.dm.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@ThreadSafe
public class StringExample2 {

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public static StringBuffer stringBuffer = new StringBuffer();

    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        long endTime = System.currentTimeMillis();
        log.info("size:{} , time:{}ms", stringBuffer.length(), (endTime - startTime));
        /**
         * 结果
         * 10:18:53.490 [main] INFO cn.dm.example.commonUnsafe.StringExample2 - size:5000
         *
         * 10:23:16.420 [main] INFO cn.dm.example.commonUnsafe.StringExample2 - size:5000 , time:15ms
         * 10:23:31.966 [main] INFO cn.dm.example.commonUnsafe.StringExample2 - size:5000 , time:17ms
         * 10:23:46.182 [main] INFO cn.dm.example.commonUnsafe.StringExample2 - size:5000 , time:15ms
         * 10:23:59.683 [main] INFO cn.dm.example.commonUnsafe.StringExample2 - size:5000 , time:16ms
         * 10:24:14.793 [main] INFO cn.dm.example.commonUnsafe.StringExample2 - size:5000 , time:15ms
         *
         * 每次拼接一个1,若是线程安全则应该等于预期值5000，经数次测试之后发现打印结果均为5000，说明StringBuffer是线程安全类
         */
    }

    private static void update() {
        stringBuffer.append("1");
    }
}
